<template>
  <div class="templates">
    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.name"
            placeholder="搜索模板名称"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.type" placeholder="模板类型" clearable>
            <el-option label="JSON" value="JSON" />
            <el-option label="XML" value="XML" />
            <el-option label="TEXT" value="TEXT" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
        <el-col :span="8" style="text-align: right">
          <el-button type="success" @click="handleAdd">新增模板</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 模板列表 -->
    <el-card class="table-card">
      <el-table :data="templates" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="模板名称" min-width="150" />
        <el-table-column prop="contentType" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.contentType)" size="small">
              {{ scope.row.contentType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="info" size="small" @click="handlePreview(scope.row)">预览</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="85%"
      top="5vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="模板类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择模板类型">
                <el-option label="JSON" value="JSON" />
                <el-option label="XML" value="XML" />
                <el-option label="TEXT" value="TEXT" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="响应头" prop="headers">
          <div class="headers-container">
            <div class="headers-toolbar">
              <el-button size="small" @click="formatHeaders">格式化JSON</el-button>
              <el-button size="small" @click="insertHeaderVariable">插入变量</el-button>
            </div>
            <el-input
              v-model="form.headers"
              type="textarea"
              :rows="4"
              placeholder="请输入JSON格式的响应头，如: {&quot;Content-Type&quot;: &quot;application/json&quot;, &quot;X-Custom-Header&quot;: &quot;${timestamp}&quot;}"
              clearable
            />
          </div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="2"
            placeholder="请输入模板描述"
          />
        </el-form-item>
        <el-form-item label="模板内容" prop="templateContent" class="template-content-item">
          <div class="editor-container">
            <div class="editor-toolbar">
              <el-button size="small" @click="formatContent">格式化</el-button>
              <el-button size="small" @click="insertVariable">插入变量</el-button>
            </div>
            <div ref="editorContainer" class="editor"></div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="模板预览"
      width="100%"
      top="10vh"
    >
      <div class="preview-content">
        <div class="preview-header">
          <el-tag :type="getTypeTagType(previewTemplate.type)" size="small">
            {{ previewTemplate.type }}
          </el-tag>
          <span class="preview-name">{{ previewTemplate.name }}</span>
        </div>
        <div class="preview-body">
          <div v-if="previewTemplate.headers" class="preview-section">
            <h4>响应头</h4>
            <div class="json-viewer">
              <pre>{{ formatJson(previewTemplate.headers) }}</pre>
            </div>
          </div>
          <div class="preview-section">
            <h4>模板内容</h4>
            <div class="json-viewer">
              <pre>{{ previewTemplate.templateContent }}</pre>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 变量插入对话框 -->
    <el-dialog
      v-model="variableDialogVisible"
      title="插入变量"
      width="400px"
    >
      <div class="variable-list">
        <h4>常用变量</h4>
        <div class="variable-item" @click="insertVariableContent('${random.int(1,100)}')">
          <strong>随机整数:</strong> ${random.int(1,100)}
        </div>
        <div class="variable-item" @click="insertVariableContent('${random.string(10)}')">
          <strong>随机字符串:</strong> ${random.string(10)}
        </div>
        <div class="variable-item" @click="insertVariableContent('${random.uuid}')">
          <strong>UUID:</strong> ${random.uuid}
        </div>
        <div class="variable-item" @click="insertVariableContent('${timestamp}')">
          <strong>时间戳:</strong> ${timestamp}
        </div>
        <div class="variable-item" @click="insertVariableContent('${request.path}')">
          <strong>请求路径:</strong> ${request.path}
        </div>
        <div class="variable-item" @click="insertVariableContent('${request.method}')">
          <strong>请求方法:</strong> ${request.method}
        </div>
        
        <h4>响应头常用变量</h4>
        <div class="variable-item" @click="insertVariableContent('${timestamp}')">
          <strong>时间戳:</strong> ${timestamp}
        </div>
        <div class="variable-item" @click="insertVariableContent('${random.uuid}')">
          <strong>请求ID:</strong> ${random.uuid}
        </div>
        <div class="variable-item" @click="insertVariableContent('${request.path}')">
          <strong>请求路径:</strong> ${request.path}
        </div>
        <div class="variable-item" @click="insertVariableContent('${request.method}')">
          <strong>请求方法:</strong> ${request.method}
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { templateApi } from '@/api'
import * as monaco from 'monaco-editor'

export default {
  name: 'Templates',
  setup() {
    const loading = ref(false)
    const submitting = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const previewVisible = ref(false)
    const variableDialogVisible = ref(false)
    const templates = ref([])
    const formRef = ref()
    const editorContainer = ref()
    let editor = null

    // 搜索表单
    const searchForm = reactive({
      name: '',
      type: ''
    })

    // 分页信息
    const pagination = reactive({
      page: 1,
      size: 10,
      total: 0
    })

    // 表单数据
    const form = reactive({
      id: null,
      name: '',
      type: 'JSON',
      description: '',
      templateContent: '',
      headers: ''
    })

    // 预览模板
    const previewTemplate = reactive({
      name: '',
      type: '',
      templateContent: '',
      headers: ''
    })

    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入模板名称', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择模板类型', trigger: 'change' }
      ],
      templateContent: [
        { required: true, message: '请输入模板内容', trigger: 'blur' }
      ]
    }

    // 获取模板列表
    const fetchTemplates = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.page,
          size: pagination.size,
          ...searchForm
        }
        const response = await templateApi.getTemplates(params)
        if (response.code === 0) {
          templates.value = response.data.records || []
          pagination.total = response.data.total || 0
        } else {
          ElMessage.error(response.message || '加载模板列表失败')
        }
      } catch (error) {
        console.error('获取模板列表失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 初始化编辑器
    const initEditor = () => {
      if (editor) {
        editor.dispose()
      }

      nextTick(() => {
        editor = monaco.editor.create(editorContainer.value, {
          value: form.templateContent,
          language: getLanguageByType(form.type),
          theme: 'vs-dark',
          automaticLayout: true,
          minimap: { enabled: false },
          scrollBeyondLastLine: false,
          fontSize: 14
        })

        // 监听内容变化
        editor.onDidChangeModelContent(() => {
          form.templateContent = editor.getValue()
        })
      })
    }

    // 根据类型获取语言
    const getLanguageByType = (type) => {
      const languageMap = {
        JSON: 'json',
        XML: 'xml',
        TEXT: 'plaintext'
      }
      return languageMap[type] || 'plaintext'
    }

    // 搜索
    const handleSearch = () => {
      pagination.page = 1
      fetchTemplates()
    }

    // 重置搜索
    const handleReset = () => {
      Object.assign(searchForm, {
        name: '',
        type: ''
      })
      pagination.page = 1
      fetchTemplates()
    }

    // 新增模板
    const handleAdd = () => {
      dialogTitle.value = '新增模板'
      Object.assign(form, {
        id: null,
        name: '',
        type: 'JSON',
        description: '',
        templateContent: '',
        headers: ''
      })
      dialogVisible.value = true
      nextTick(() => {
        initEditor()
      })
    }

    // 编辑模板
    const handleEdit = (row) => {
      dialogTitle.value = '编辑模板'
      Object.assign(form, row)
      dialogVisible.value = true
      nextTick(() => {
        initEditor()
      })
    }

    // 预览模板
    const handlePreview = (row) => {
      Object.assign(previewTemplate, row)
      previewVisible.value = true
    }

    // 删除模板
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除这个模板吗？', '确认删除', {
          type: 'warning'
        })
        const response = await templateApi.deleteTemplate(row.id)
        if (response.code === 0) {
          ElMessage.success('删除成功')
          fetchTemplates()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
          console.error(error)
        }
      }
    }

    // 格式化内容
    const formatContent = () => {
      if (editor) {
        editor.getAction('editor.action.formatDocument').run()
      }
    }

    // 格式化响应头
    const formatHeaders = () => {
      try {
        if (form.headers) {
          const formatted = JSON.stringify(JSON.parse(form.headers), null, 2)
          form.headers = formatted
          ElMessage.success('响应头格式化成功')
        }
      } catch (error) {
        ElMessage.error('响应头JSON格式错误')
      }
    }

    // 插入变量
    const insertVariable = () => {
      variableDialogVisible.value = true
    }

    // 插入响应头变量
    const insertHeaderVariable = () => {
      variableDialogVisible.value = true
    }

    // 插入变量内容
    const insertVariableContent = (variable) => {
      if (editor) {
        const selection = editor.getSelection()
        editor.executeEdits('', [{
          range: selection,
          text: variable
        }])
      }
      variableDialogVisible.value = false
    }

    // 提交表单
    const handleSubmit = async () => {
      try {
        submitting.value = true
        
        if (form.id) {
          const response = await templateApi.updateTemplate(form.id, form)
          if (response.code === 0) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            fetchTemplates()
          } else {
            ElMessage.error(response.message || '更新失败')
          }
        } else {
          const response = await templateApi.createTemplate(form)
          if (response.code === 0) {
            ElMessage.success('创建成功')
            dialogVisible.value = false
            fetchTemplates()
          } else {
            ElMessage.error(response.message || '创建失败')
          }
        }
      } catch (error) {
        ElMessage.error('操作失败')
        console.error(error)
      } finally {
        submitting.value = false
      }
    }

    // 对话框关闭
    const handleDialogClose = () => {
      if (formRef.value) {
        formRef.value.resetFields()
      }
      if (editor) {
        editor.dispose()
        editor = null
      }
    }

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size
      pagination.page = 1
      fetchTemplates()
    }

    const handleCurrentChange = (page) => {
      pagination.page = page
      fetchTemplates()
    }

    // 获取类型标签类型
    const getTypeTagType = (type) => {
      const typeMap = {
        JSON: 'success',
        XML: 'warning',
        TEXT: 'info'
      }
      return typeMap[type] || 'info'
    }

    // 格式化时间
    const formatTime = (timestamp) => {
      return new Date(timestamp).toLocaleString('zh-CN')
    }

    // 格式化JSON
    const formatJson = (json) => {
      if (!json) return ''
      try {
        if (typeof json === 'string') {
          return JSON.stringify(JSON.parse(json), null, 2)
        }
        return JSON.stringify(json, null, 2)
      } catch (error) {
        return json
      }
    }

    onMounted(() => {
      fetchTemplates()
    })

    return {
      loading,
      submitting,
      dialogVisible,
      dialogTitle,
      previewVisible,
      variableDialogVisible,
      templates,
      form,
      previewTemplate,
      searchForm,
      pagination,
      rules,
      formRef,
      editorContainer,
      handleSearch,
      handleReset,
      handleAdd,
      handleEdit,
      handlePreview,
      handleDelete,
      formatContent,
      formatHeaders,
      insertVariable,
      insertHeaderVariable,
      insertVariableContent,
      handleSubmit,
      handleDialogClose,
      handleSizeChange,
      handleCurrentChange,
      getTypeTagType,
      formatTime,
      formatJson
    }
  }
}
</script>

<style scoped>
.templates {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 100%;
  min-width: 100%;
}

.editor-toolbar {
  padding: 8px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
}

.editor {
  height: 500px;
  min-height: 400px;
  width: 100%;
}

.template-content-item {
  margin-bottom: 20px;
}

.template-content-item .el-form-item__content {
  width: 100%;
}

.headers-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 100%;
}

.headers-toolbar {
  padding: 8px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  gap: 8px;
}

.preview-content {
  max-height: 500px;
  overflow: auto;
}

.preview-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.preview-name {
  margin-left: 10px;
  font-weight: bold;
  color: #303133;
}

.preview-body {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.json-viewer {
  background-color: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  max-height: 200px;
  overflow-y: auto;
}

.preview-body pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.5;
}

.preview-section {
  margin-bottom: 20px;
}

.preview-section h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
  font-weight: bold;
}

.variable-list {
  max-height: 300px;
  overflow-y: auto;
}

.variable-list h4 {
  margin: 15px 0 10px 0;
  color: #303133;
  font-size: 14px;
  font-weight: bold;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 5px;
}

.variable-list h4:first-child {
  margin-top: 0;
}

.variable-item {
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.variable-item:hover {
  background-color: #f5f7fa;
  border-color: #409eff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 